package cn.livingCloud.controller.core.validator;

import cn.livingCloud.dto.CaseFormDto;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.util.regex.Pattern;

/**
 * Created by DingJie on 2016/6/3.
 */
@Component
public class CaseFormDtoValidator implements Validator {
    public static final String PHONE_REGULAR = "1[0-9]{10}";

    @Override
    public boolean supports(Class<?> aClass) {
        return CaseFormDto.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        CaseFormDto formDto = (CaseFormDto) o;
        validateImageList(formDto, errors);
        validatePhone(formDto, errors);
        validateAddressDescription(formDto, errors);
        validateLocation(formDto, errors);
        validateCreator(formDto, errors);
    }

    private void validateCreator(CaseFormDto formDto, Errors errors) {
        if (StringUtils.isEmpty(formDto.getCreatorUuid())) {
            errors.rejectValue("creatorUuid", null, "请搜索并选择创建人");
        }
    }

    private void validateImageList(CaseFormDto formDto, Errors errors) {
        if (formDto.getImageList().size() < 1) {
            errors.rejectValue("imageList", null, "至少上传一张图片");
        }
    }

    private void validateLocation(CaseFormDto formDto, Errors errors) {
        if (StringUtils.isEmpty(formDto.getLocationX())) {
            errors.rejectValue("locationX", null, "经纬度不能为空");
        }
        if (StringUtils.isEmpty(formDto.getLocationY())) {
            errors.rejectValue("locationY", null, "经纬度不能为空");
        }
    }

    private void validateAddressDescription(CaseFormDto formDto, Errors errors) {
        if (StringUtils.isEmpty(formDto.getAddressDescription())) {
            errors.rejectValue("addressDescription", null, "内容不能为空");
            return;
        }
        if (formDto.getAddressDescription().length() > 200) {
            errors.rejectValue("addressDescription", null, "内容不能超过200字");
        }
    }

    private void validatePhone(CaseFormDto formDto, Errors errors) {
//        if (StringUtils.isEmpty(formDto.getPhone())) {
//            errors.rejectValue("phone", null, "请填写手机号码");
//            return;
//        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(formDto.getPhone()) && !validateIsPhoneNumber(formDto)) {
            errors.rejectValue("phone", null, "请输入正确的手机号!");
        }
    }

    private boolean validateIsPhoneNumber(CaseFormDto formDto) {
        return Pattern.compile(PHONE_REGULAR).matcher(formDto.getPhone()).matches();
    }
}
